import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Storage extends StatefulWidget {
  const Storage({super.key});

  @override
  State<Storage> createState() => _StorageState();
}

class _StorageState extends State<Storage> {
  String countString = '';
  String localCount = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('storage实现计数器')),
      body: Column(
        children: [
          ElevatedButton(onPressed: _incrementCounter, child: const Text('Increment Counter')),
          ElevatedButton(onPressed: _getCounter, child: const Text('Get Counter')),
          Text(countString,style: const TextStyle(fontSize: 20),),
          Text('result:$localCount', style: const TextStyle(fontSize: 20))
        ],
      ),
    );
  }

  void _incrementCounter() async {
    setState(() {
      countString = '$countString 1';
    });

    SharedPreferences prefs = await SharedPreferences.getInstance();
    int newCounter = (prefs.getInt('counter') ?? 0) + 1;
    await prefs.setInt('counter', newCounter);
  }

  void _getCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      localCount = (prefs.getInt('counter') ?? 0).toString();
    });
  }
}
